﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraControl1 : MonoBehaviour
{
    public float m_DampTime = 0.2f;
    public float m_ScreenEdgeBuffer = 4f;
    public float m_MinSize = 6.5f;
    [HideInInspector] public Transform[] m_Targets;

    private Camera m_Camera;
    private float m_ZoomSpeed;
    private Vector3 m_MoveVelocity;
    private Vector3 m_DesiredPos;

    private void Awake()
    {
        m_Camera = GetComponentInChildren<Camera>();
    }

    private void FixedUpdate()
    {
        Move();
        Zoom();
    }

    void Move()
    {
        FindAveragePosition();
        transform.position = Vector3.SmoothDamp(transform.position, m_DesiredPos,ref m_MoveVelocity,m_DampTime);
    }

    void FindAveragePosition()
    {
        Vector3 averagePos = new Vector3();
        float num = 0;
        for (int i = 0;i < m_Targets.Length; i++)
        {
            if (!m_Targets[i].gameObject.activeSelf)
                continue;
            num++;
            averagePos += m_Targets[i].transform.position;
        }
        if(num > 0)
            averagePos /= num;
        averagePos.y = transform.position.y;
        m_DesiredPos = averagePos;
    }

    void Zoom()
    {
        float desiredSize = FindRequiredSize();
        m_Camera.orthographicSize = Mathf.SmoothDamp(m_Camera.orthographicSize,desiredSize,ref m_ZoomSpeed,m_DampTime);
    }

    float FindRequiredSize()
    {
        float size = 0f;
        Vector3 desiredPos = transform.InverseTransformPoint(transform.position);

        for(int i = 0;i < m_Targets.Length; i++)
        {
            if(!m_Targets[i].gameObject.activeSelf)
                continue ;
            Vector3 targetLocalPos = transform.InverseTransformPoint(m_Targets[i].position);
            desiredPos = targetLocalPos - desiredPos;
            size = Mathf.Max(size, Mathf.Abs(desiredPos.x));
            size = Mathf.Max(size,Mathf.Abs(desiredPos.y/m_Camera.aspect));
        }

        size += m_ScreenEdgeBuffer;
        Mathf.Max(size,m_MinSize);

        return size;
    }


    public void SetStartPositionAndSize()
    {
        FindAveragePosition();
        transform.position = m_DesiredPos;
        m_Camera.orthographicSize = FindRequiredSize();
    }
}
